package cmd

import (
	global2 "longmen/server/config/global"
	v5 "longmen/server/internal/services/nami/api"
	"longmen/server/internal/services/nami/api/v5/esports"
	"longmen/server/internal/services/nami/api/v5/sports"
	"longmen/server/internal/services/nami/config"
	"os"
	"os/signal"
	"syscall"

	"github.com/robfig/cron/v3"
	"github.com/spf13/cobra"
)

var crontab = cron.New(cron.WithSeconds())
var SyncHandlers = []v5.SetUpTask{
	esports.SetUpTask,
	sports.SetUpTask,
}
var runServer = &cobra.Command{
	Use:   "run",
	Short: "run cronjob server",
	Long:  "run cronjob server",
	Run: func(cmd *cobra.Command, args []string) {
		for i := 0; i < len(SyncHandlers); i++ {
			SyncHandlers[i](crontab)
		}
		crontab.Start()
		//pyroscope.InitPyroScope("nami")
		//创建监听退出chan
		c := make(chan os.Signal, 1)
		//监听指定信号 ctrl+c kill
		signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGUSR1, syscall.SIGUSR2)
		for s := range c {
			switch s {
			case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
				global2.Log.Info("退出信号： ", s)
				stop := crontab.Stop()

				global2.Log.Info("退出等待", stop.Done())
				os.Exit(0)
			default:
				global2.Log.Info("未知信号", s)
			}
		}
	},
	PreRun: func(cmd *cobra.Command, args []string) {
		global2.Initialize(configFile)
		config.InitConfig()
		err := global2.InitElasticSearch()
		if err != nil {
			global2.Log.Fatalf("%s", err.Error())
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {

	},
}
